package com.yhk.wuchat.common.websocket;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.yhk.wuchat.common.websocket.domain.enums.WSReqTypeEnum;
import com.yhk.wuchat.common.websocket.domain.vo.req.WSBaseReq;
import com.yhk.wuchat.common.websocket.service.WebSocketService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义websocket处理器
 */
@Slf4j
@Sharable
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {


    private WebSocketService webSocketService;

    /**
     * 建立连接之后,开始生效
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //获取spring容器中的bean
        webSocketService = SpringUtil.getBean(WebSocketService.class);
        //用户上线
        webSocketService.connect(ctx.channel());
    }

    /**
     * 用户主动下线
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        userOffline(ctx.channel());
    }

    /**
     * 监听连接事件
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
            System.out.println("握手完成");
            //获取token
            String token = NettyUtil.getAttr(ctx.channel(), NettyUtil.TOKEN);
            if (StrUtil.isNotBlank(token)) {
                //如果token不为空，进行登录认证
                webSocketService.authorize(ctx.channel(),token);
            }
        }else if(evt instanceof IdleStateEvent){
            IdleStateEvent idleStateEvent=(IdleStateEvent) evt;
            if(idleStateEvent.state()==IdleState.READER_IDLE){
                System.out.println("读空闲");
                // 用户下线
                userOffline(ctx.channel());
            }
        }
    }

    /**
     * 用户下线，统一关闭
     * @param channel
     */
    private void userOffline(Channel channel) {
        webSocketService.remove(channel);
        channel.close();
    }

    /**
     * 异常处理
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("异常发生，异常消息 ={}", cause.getMessage());
        super.exceptionCaught(ctx, cause);
    }

    /**
     * 读取客户端发送的请求报文
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        String test= msg.text();
        //接收用户传来的信息，并将他反序列化
        WSBaseReq wsBaseReq = JSONUtil.toBean(test, WSBaseReq.class);
        switch (WSReqTypeEnum.of(wsBaseReq.getType())) {
            case LOGIN:
                webSocketService.handlerLoginReq(ctx.channel());
                log.info("请求二维码，{}", test);
                break;
            case AUTHORIZE:
                webSocketService.authorize(ctx.channel(),wsBaseReq.getData());
                log.info("登录认证，{}",wsBaseReq.getData());
                break;
        }
    }
}
